'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';

interface Brand {
  brand: string;
  name: string;
  alphabet: string;
  country: string;
  hot: string;
  desc: string;
  story: string;
}

interface Car {
  id: string;
  name: string;
  brand: string;
  type: string;
  price: number;
  image: string;
  year: number;
  power: string;
  range: string;
}

export default function BrandDetailPage() {
  const { user } = useAuth();
  const router = useRouter();
  const params = useParams();
  const brandKey = params.brand as string;

  const [brand, setBrand] = useState<Brand | null>(null);
  const [brands, setBrands] = useState<Brand[]>([]);
  const [cars, setCars] = useState<Car[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'overview' | 'cars' | 'story'>('overview');

  useEffect(() => {
    if (!user || user.role !== 'admin') {
      router.push('/login');
      return;
    }

    const loadData = async () => {
      try {
        const brandData = await import('@/../public/brandData.js');
        const allBrands = brandData.default;
        setBrands(allBrands);
        
        const currentBrand = allBrands.find(b => b.brand === brandKey);
        setBrand(currentBrand || null);

        // 模拟车辆数据
        const mockCars: Car[] = [
          { id: '1', name: 'Model S Plaid', brand: 'tesla', type: '纯电动轿车', price: 1028900, image: '/cars/tesla-model-s.jpg', year: 2024, power: '1020马力', range: '637公里' },
          { id: '2', name: 'Model 3', brand: 'tesla', type: '纯电动轿车', price: 231900, image: '/cars/tesla-model-3.jpg', year: 2024, power: '450马力', range: '567公里' },
          { id: '3', name: 'Model Y', brand: 'tesla', type: '纯电动SUV', price: 263900, image: '/cars/tesla-model-y.jpg', year: 2024, power: '450马力', range: '533公里' },
          { id: '4', name: '汉EV冠军版', brand: 'byd', type: '纯电动轿车', price: 219800, image: '/cars/byd-han.jpg', year: 2024, power: '517马力', range: '715公里' },
          { id: '5', name: '唐DM-p', brand: 'byd', type: '插电混动SUV', price: 309800, image: '/cars/byd-tang.jpg', year: 2024, power: '615马力', range: '215公里' },
          { id: '6', name: '海豚', brand: 'byd', type: '纯电动小型车', price: 116800, image: '/cars/byd-dolphin.jpg', year: 2024, power: '177马力', range: '420公里' },
          { id: '7', name: '理想L9 Max', brand: 'li', type: '增程式SUV', price: 459800, image: '/cars/li-l9.jpg', year: 2024, power: '449马力', range: '215公里' },
          { id: '8', name: '理想L7', brand: 'li', type: '增程式SUV', price: 319800, image: '/cars/li-l7.jpg', year: 2024, power: '449马力', range: '210公里' },
          { id: '9', name: '小鹏G9', brand: 'xiaopeng', type: '纯电动SUV', price: 309900, image: '/cars/xpeng-g9.jpg', year: 2024, power: '551马力', range: '702公里' },
          { id: '10', name: '小鹏P7i', brand: 'xiaopeng', type: '纯电动轿车', price: 249900, image: '/cars/xpeng-p7.jpg', year: 2024, power: '473马力', range: '610公里' },
        ];

        const brandCars = mockCars.filter(car => car.brand === brandKey);
        setCars(brandCars);
      } catch (error) {
        console.error('加载数据失败:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadData();
  }, [user, router, brandKey]);

  if (!user || user.role !== 'admin') {
    return null;
  }

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (!brand) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">🚗</div>
          <h2 className="text-2xl font-bold text-gray-900 mb-2">品牌未找到</h2>
          <p className="text-gray-600 mb-4">您访问的品牌不存在</p>
          <Link href="/admin/brands" className="text-blue-600 hover:text-blue-700">
            返回品牌列表
          </Link>
        </div>
      </div>
    );
  }

  const brandCars = cars.filter(car => car.brand === brand.brand);
  const relatedBrands = brands.filter(b => b.country === brand.country && b.brand !== brand.brand).slice(0, 4);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between py-6">
            <div className="flex items-center space-x-4">
              <Link 
                href="/admin/brands"
                className="text-gray-400 hover:text-gray-600 transition-colors"
              >
                ← 返回品牌列表
              </Link>
              <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white text-xl font-bold">
                {brand.alphabet}
              </div>
              <div>
                <h1 className="text-3xl font-bold text-gray-900">{brand.name}</h1>
                <p className="text-gray-600">{brand.country}</p>
              </div>
            </div>
            {brand.hot === '1' && (
              <span className="px-4 py-2 bg-red-100 text-red-600 text-sm font-semibold rounded-full">
                热门品牌
              </span>
            )}
          </div>
        </div>
      </div>

      {/* Navigation Tabs */}
      <div className="bg-white border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <nav className="flex space-x-8">
            {[
              { id: 'overview', label: '品牌概览' },
              { id: 'cars', label: `车型推荐 (${brandCars.length})` },
              { id: 'story', label: '品牌故事' },
            ].map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors ${
                  activeTab === tab.id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </nav>
        </div>
      </div>

      {/* Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* Main Content */}
          <div className="lg:col-span-3">
            {activeTab === 'overview' && (
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h2 className="text-2xl font-bold text-gray-900 mb-4">品牌介绍</h2>
                <p className="text-gray-700 leading-relaxed text-lg mb-6">
                  {brand.desc}
                </p>
                
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                  <div className="bg-blue-50 rounded-lg p-4">
                    <h3 className="font-semibold text-blue-900 mb-2">品牌特色</h3>
                    <ul className="text-blue-800 space-y-1">
                      <li>• 技术创新领先</li>
                      <li>• 产品质量可靠</li>
                      <li>• 用户口碑优秀</li>
                      <li>• 市场表现突出</li>
                    </ul>
                  </div>
                  <div className="bg-green-50 rounded-lg p-4">
                    <h3 className="font-semibold text-green-900 mb-2">核心优势</h3>
                    <ul className="text-green-800 space-y-1">
                      <li>• 研发实力雄厚</li>
                      <li>• 服务体系完善</li>
                      <li>• 品牌影响力强</li>
                      <li>• 可持续发展</li>
                    </ul>
                  </div>
                </div>

                {/* Quick Stats */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-gray-900">{brandCars.length}</div>
                    <div className="text-sm text-gray-600">在售车型</div>
                  </div>
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-gray-900">
                      {brandCars.length > 0 ? Math.min(...brandCars.map(c => c.price)).toLocaleString() : '0'}
                    </div>
                    <div className="text-sm text-gray-600">起售价(元)</div>
                  </div>
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-gray-900">
                      {brandCars.length > 0 ? Math.max(...brandCars.map(c => c.price)).toLocaleString() : '0'}
                    </div>
                    <div className="text-sm text-gray-600">最高价(元)</div>
                  </div>
                  <div className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className="text-2xl font-bold text-gray-900">2024</div>
                    <div className="text-sm text-gray-600">最新车型</div>
                  </div>
                </div>
              </div>
            )}

            {activeTab === 'cars' && (
              <div>
                <h2 className="text-2xl font-bold text-gray-900 mb-6">推荐车型</h2>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {brandCars.map(car => (
                    <div key={car.id} className="bg-white rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-shadow">
                      <div className="p-6">
                        <div className="flex justify-between items-start mb-4">
                          <div>
                            <h3 className="text-xl font-semibold text-gray-900">{car.name}</h3>
                            <p className="text-gray-600">{car.type}</p>
                          </div>
                          <span className="bg-blue-100 text-blue-600 px-3 py-1 rounded-full text-sm font-medium">
                            {car.year}款
                          </span>
                        </div>
                        
                        <div className="grid grid-cols-2 gap-4 mb-4">
                          <div className="text-center p-3 bg-gray-50 rounded-lg">
                            <div className="text-sm text-gray-600">动力</div>
                            <div className="font-semibold text-gray-900">{car.power}</div>
                          </div>
                          <div className="text-center p-3 bg-gray-50 rounded-lg">
                            <div className="text-sm text-gray-600">续航</div>
                            <div className="font-semibold text-gray-900">{car.range}</div>
                          </div>
                        </div>
                        
                        <div className="flex justify-between items-center">
                          <span className="text-2xl font-bold text-blue-600">
                            {car.price.toLocaleString()}元
                          </span>
                          <button className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors">
                            查看详情
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {activeTab === 'story' && (
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h2 className="text-2xl font-bold text-gray-900 mb-6">品牌故事</h2>
                <div className="prose prose-lg max-w-none text-gray-700 leading-relaxed">
                  <p className="text-lg mb-6">
                    {brand.story}
                  </p>
                  
                  <div className="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-6">
                    <p className="text-yellow-700">
                      <strong>品牌里程碑：</strong> 从创立至今，{brand.name}始终坚持创新驱动发展，在技术研发、产品设计、用户体验等方面不断突破，成为行业标杆。
                    </p>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-8">
                    <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-6">
                      <h3 className="font-semibold text-blue-900 mb-3">技术创新</h3>
                      <p className="text-blue-800">
                        {brand.name}在核心技术领域持续投入，推动行业技术进步，为用户带来更优质的产品体验。
                      </p>
                    </div>
                    <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-6">
                      <h3 className="font-semibold text-green-900 mb-3">市场表现</h3>
                      <p className="text-green-800">
                        凭借卓越的产品力和品牌影响力，{brand.name}在全球市场取得了显著成就，赢得用户广泛认可。
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Sidebar */}
          <div className="lg:col-span-1">
            {/* Related Brands */}
            {relatedBrands.length > 0 && (
              <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
                <h3 className="font-semibold text-gray-900 mb-4">同国家品牌</h3>
                <div className="space-y-3">
                  {relatedBrands.map(brand => (
                    <Link
                      key={brand.brand}
                      href={`/admin/brands/${brand.brand}`}
                      className="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-50 transition-colors group"
                    >
                      <div className="w-8 h-8 bg-gradient-to-br from-gray-400 to-gray-600 rounded-full flex items-center justify-center text-white text-sm font-bold">
                        {brand.alphabet}
                      </div>
                      <div className="flex-1">
                        <div className="font-medium text-gray-900 group-hover:text-blue-600 transition-colors">
                          {brand.name}
                        </div>
                        <div className="text-sm text-gray-500">{brand.desc.slice(0, 20)}...</div>
                      </div>
                    </Link>
                  ))}
                </div>
              </div>
            )}

            {/* Quick Actions */}
            <div className="bg-white rounded-lg shadow-sm p-6">
              <h3 className="font-semibold text-gray-900 mb-4">快速操作</h3>
              <div className="space-y-3">
                <button className="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition-colors">
                  添加新车型
                </button>
                <button className="w-full border border-gray-300 text-gray-700 py-2 px-4 rounded-lg hover:bg-gray-50 transition-colors">
                  编辑品牌信息
                </button>
                <button className="w-full border border-gray-300 text-gray-700 py-2 px-4 rounded-lg hover:bg-gray-50 transition-colors">
                  查看销售数据
                </button>
              </div>
            </div>

            {/* Brand Stats */}
            <div className="bg-white rounded-lg shadow-sm p-6 mt-6">
              <h3 className="font-semibold text-gray-900 mb-4">品牌数据</h3>
              <div className="space-y-3">
                <div className="flex justify-between">
                  <span className="text-gray-600">车型数量</span>
                  <span className="font-semibold">{brandCars.length}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">价格区间</span>
                  <span className="font-semibold">
                    {brandCars.length > 0 ? `${Math.min(...brandCars.map(c => c.price)).toLocaleString()} - ${Math.max(...brandCars.map(c => c.price)).toLocaleString()}元` : '暂无数据'}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">最新车型</span>
                  <span className="font-semibold">2024款</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">热门程度</span>
                  <span className="font-semibold">
                    {brand.hot === '1' ? '热门' : '一般'}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}